package sdk.webview.fmc.com.fmcsdk.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.ExifInterface;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.widget.ImageView;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class ImageUtils {


    private static Uri iamgeUri;

    /**
     * 加载首页功能图标，缓存-本地-网络三级存储（首页图片生成缩略图会变黑，所以没有缩略图）
     *
     * @param context         上下文
     * @param picurl          图片链接
     * @param imageName       图片名称
     * @param imageView       显示图片的控件
     * @param defaultResource 默认显示图片
     */
    public static void handleIconImage(final Context context, final String picurl, final String imageName, final ImageView imageView, final int defaultResource) {

        File file = new File(getImagePath(imageName, context));
        if (file.exists()) {
//				XLog.i("handleIconImage本地有"+imageName,context);
            //本地获取
            try {
                Bitmap localBitmap = BitmapFactory.decodeFile(getImagePath(imageName, context));
                if (localBitmap == null) {
                    imageView.setImageResource(defaultResource);
                } else {
                    imageView.setImageBitmap(localBitmap);
                }
            } catch (Exception e) {
                e.printStackTrace();
                imageView.setImageResource(defaultResource);
            }
        } else {//网络下载
            down(context, picurl, file, new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case 0://下载失败
                            imageView.setImageResource(defaultResource);
                            break;
                        case 1://下载成功
                            try {
                                Bitmap localBitmap = BitmapFactory.decodeFile(getImagePath(imageName, context));
                                if (localBitmap != null) {
                                    imageView.setImageBitmap(localBitmap);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                imageView.setImageResource(defaultResource);
                            }
                            break;
                    }
                }
            });
        }
    }

    /**
     * 生成缩略图并保存
     *
     * @param bitmap
     * @param picName
     */
    public static void saveThumBitmap(Bitmap bitmap, String picName, ImageView imageView, Context context) {
        if (null == bitmap) {
            return;
        }
        String thumPath = getThumbernailPath(picName, context);
        File thumFile = new File(thumPath);
        Bitmap thumBitmap = getThumbnail(bitmap, 100, 100, 80);
        if (imageView != null) {
            imageView.setImageBitmap(thumBitmap);
        }

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(thumFile);
            thumBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    /**
     * 下载图片，放入缓存，并生成缩略图保存到本地
     *
     * @param context
     * @param picurl
     * @param fileName
     * @param
     */
    public static void downloadImage(final Context context, final String picurl, final String fileName, final SharedPreferences sharedPrefs) {

        final File localFile = new File(getImagePath2(fileName, context));
        if (localFile.exists()) {
            localFile.delete();
        }
        final Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:// 下载失败
                        break;
                    case 1:
                        //下载成功
                        Bitmap source = getCompressBitmap(context, getImagePath2(fileName, context));
                        // 文件有误
                        if (source == null) {
                            localFile.delete();
                            return;
                        }
                        XLog.i("下载图片成功 fileName=：" + fileName, context);
                        if (fileName.contains(Constant.MAIN_BG)) {
                            sharedPrefs.edit().putString(Constant.MAIN_BG, fileName).apply();
                        } else if (fileName.contains(Constant.START_BG)) {
                            sharedPrefs.edit().putString(Constant.START_BG, fileName).apply();
                        } else if (fileName.contains(Constant.ABOUT_BG)) {
//						XLog.i("下载图片成功 aboutbj："+fileName);
                            sharedPrefs.edit().putString(Constant.ABOUT_BG, fileName).apply();
                        }
                        // 生成缩略图并放入缓存
                        saveThumBitmap(source, fileName, null, context);
                        break;
                    default:
                        break;
                }
            }

            ;
        };
        //开始下载图片
        down(context, picurl, localFile, handler);
    }


    /**
     * 新开线程下载图片
     *
     * @param picurl    图片链接
     * @param localFile 要保存的文件
     * @param handler   要接收下载结果的handler
     */
    public static void down(final Context context, final String picurl, final File localFile, final Handler handler) {
        int i = Process.myTid();

        if (TextUtils.isEmpty(picurl))
            return;
        new Thread(new Runnable() {

            @Override
            public void run() {
                int i = Process.myTid();
                InputStream is = null;
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(localFile);
//					Url url = new Url(getRealUrl(context,picurl));
                    URL url = new URL(picurl);
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    if (picurl.startsWith("https")) {
                        boolean isSdk = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(Constant.IS_SDK, false);
                        if (!isSdk) {
                            String appName = (String) Utility.getMetaData(context, Constant.APP_NAME);
                            String isHttps = (String) Utility.getMetaData(context, Constant.IS_HTTPS_TEST);
//							if (Constant.APP_NAME_BAQ.equals(appName)||isHttps.equals("fmc_true")) {
//								HttpsManager.setHttpsConnection(conn, context);
//							}
                        }

                    }

                    conn.connect();
                    is = conn.getInputStream();
                    byte buf[] = new byte[1024];
                    do {
                        int numread = is.read(buf);
                        if (numread <= 0) {
                            // 下载完成
                            handler.sendEmptyMessage(1);
                            break;
                        }
                        fos.write(buf, 0, numread);
                    } while (true);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(0);
                } catch (IOException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(0);
                } catch (Exception e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(0);
                } finally {
                    try {
                        if (fos != null)
                            fos.close();
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        }).start();
    }


    public static String getThumbernailPath(String imageName, Context context) {

        String storePath;
        if (SdkVersionUtils.checkedAndroid_R()) {
            storePath = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.APP_NAME, "fmsdk");
        } else {
            storePath = context.getFilesDir().getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.APP_NAME, "fmsdk");

        }

        return storePath + Constant.IMAGEPATH + File.separator + "th_" + imageName;
    }

    //
    public static String getImagePath(String imageName, Context context) {
//        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.APP_NAME, "fmsdk");

        String storePath = context.getExternalFilesDir(null).getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.APP_NAME, "fmsdk");
//		String storePath;
//		if (SdkVersionUtils.checkedAndroid_R()) {
//			storePath =context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.APP_NAME, "fmsdk");
//		} else {
//			storePath = context.getFilesDir().getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.APP_NAME, "fmsdk");
//
//		}

        File file = new File(storePath + Constant.IMAGEPATH);
        if (!file.exists()) {
            file.mkdirs();
        }
        return storePath + Constant.IMAGEPATH + File.separator + imageName;
    }

    public static String getImagePath2(String imageName, Context context) {
//		String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.APP_NAME, "fmsdk");
        String storePath;
        if (SdkVersionUtils.checkedAndroid_R()) {
            storePath = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.APP_NAME, "fmsdk");
        } else {
            storePath = context.getFilesDir().getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.APP_NAME, "fmsdk");

        }

        File file = new File(storePath + Constant.IMAGEPATH);
        if (!file.exists()) {
            file.mkdirs();
        }
        return storePath + Constant.IMAGEPATH + File.separator + imageName;
    }

    //获取H5图的路径
    public static String getH5ImagePath(String imageName, Context context) {
//		String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.APP_NAME, "fmsdk");
        String storePath;
        if (SdkVersionUtils.checkedAndroid_R()) {
            storePath = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.APP_NAME, "fmsdk");
        } else {
            storePath = context.getFilesDir().getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.APP_NAME, "fmsdk");
        }

        File file = new File(storePath + Constant.H5IMAGEPATH);
        if (!file.exists()) {
            file.mkdirs();
        }
        String pathUrl=storePath + Constant.H5IMAGEPATH + File.separator + imageName;
        XLog.i(storePath + Constant.H5IMAGEPATH + File.separator + imageName);
        return pathUrl;
    }

    private static void deleteFiles(File dir) {
        if (dir == null || !dir.exists() || dir.listFiles() == null) return;
        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                deleteFiles(file);
            } else {
                file.delete();
            }
        }
        dir.delete();
    }


    //获取H5缩略图的路径
    public static String getH5ImageThumPath(String imageName, Context context) {
//		String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.APP_NAME, "fmsdk");
        String storePath;
        if (SdkVersionUtils.checkedAndroid_R()) {
            storePath = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.APP_NAME, "fmsdk");
        } else {
            storePath = context.getFilesDir().getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.APP_NAME, "fmsdk");

        }

        File file = new File(storePath + Constant.H5IMAGEPATH);
        if (!file.exists()) {
            file.mkdirs();
        }
        return storePath + Constant.H5IMAGEPATH + File.separator + "th_" + imageName;
    }


    @SuppressLint("SimpleDateFormat")
    public static String getImageName(Context context) {
        String fileName = "";
//		Date date = DateUtil.getServerDate(context);
//		try {
//			SimpleDateFormat dateForamt = new SimpleDateFormat("yyyyMMddHHmmss");
//			fileName = dateForamt.format(date);
//		} catch (Exception e) {
//			fileName = String.valueOf(date.getTime());
//		}
        fileName = System.currentTimeMillis() + "" + (int) ((Math.random() * 9 + 1) * 100000);
        XLog.i(fileName + "");
        return fileName;
    }

    /**
     * base64转为bitmap
     *
     * @param base64Data
     * @return
     */
    public static void base64ToBitmap(String base64Data, String imageName) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        if (bitmap == null) {
            return;
        }
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] b = stream.toByteArray(); // 将图片流以字符串形式存储下来
        FileOutputStream fos = null;
        try {

            File file = new File(imageName);
            if (file.exists()) {
                file.delete();
            }
            fos = new FileOutputStream(file);
            fos.write(b);
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
        }
    }


    /**
     * 获取缩略图
     *
     * @param source
     * @param width
     * @param height
     * @param options
     * @return
     */
    public static Bitmap getThumbnail(Bitmap source, int width, int height,
                                      int options) {
        return ThumbnailUtils.extractThumbnail(source, width, height, options);
    }

    /**
     * 压缩图片
     *
     * @param pathName
     * @return
     */
    public static Bitmap compress(Context context, String pathName) {
        return compress(context, pathName, 320f, 480f);
    }

    /**
     * 压缩图片
     *
     * @param pathName
     * @param ww
     * @param hh
     * @return
     */
    public static Bitmap compress(Context context, String pathName, float ww, float hh) {
        File file = new File(pathName);
        if (!file.exists()) {
            return null;
        }
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;    //只是获取图片信息而不是真正的图片
        BitmapFactory.decodeFile(pathName, opts);
        opts.inJustDecodeBounds = false;
        int w = opts.outWidth;
        int h = opts.outHeight;
        int be = 1;
        if (w > h && w > ww) {
            be = (int) (opts.outWidth / ww);
        } else if (w < h && h > hh) {
            be = (int) (opts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        opts.inSampleSize = be;
        opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
        opts.inPurgeable = true;
        opts.inInputShareable = true;

        Bitmap bitmap = decodeFile(context, pathName, opts);
        if (bitmap == null) {
            bitmap = BitmapFactory.decodeFile(pathName, opts);
        }
        return bitmap;
    }

    public static Bitmap decodeFile(Context context, String path, BitmapFactory.Options opts) {
        FileInputStream fis = null;
        Bitmap bitmap = null;
        try {
            fis = new FileInputStream(path);
            bitmap = BitmapFactory.decodeFileDescriptor(fis.getFD(), null, opts);
//			int degree = readPictureDegree(path);
//			if (degree == 90 || degree == 270)
//				bitmap = rotaingImageView(90,bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bitmap;
    }


    /**
     * 获取压缩后的图片，比手机屏幕大就缩小至全屏大小，否则返回原图
     *
     * @param context
     * @param path
     * @return
     */
    public static Bitmap getCompressBitmap(Context context, String path) {
        DisplayMetrics metrics = Utility.getDisplayMetrics(context);
        return compress(context, path, metrics.widthPixels, metrics.heightPixels);
    }

    /**
     * 获取图片信息
     *
     * @param path
     * @return
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;

    }

    /**
     * 图片旋转
     *
     * @param angle
     * @param bitmap
     * @return
     */
    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        // 旋转图片 动作
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }

    /*
     * 按指定尺寸压缩并保存图片
     * @param context
     * @param pathName
     * @param width
     * @param height
     */
    public static void compressAndSave(Context context, String pathName, int width, int height) {
        Bitmap bitmap = compress(context, pathName, width, height);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(pathName);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            bitmap.recycle();
            fos.flush();
        } catch (Exception e) {

        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {

                }
            }
        }
    }


    public static void compressIamge(Activity context, String filename) {


        String imageSizeStr = PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.IMAGE_SIZE, "50");
        int imageSize = Integer.parseInt(imageSizeStr);

        String srcPath = getH5ImagePath(filename, context);
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        float hh = dm.heightPixels;
        float ww = dm.widthPixels;
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, opts);
        opts.inJustDecodeBounds = false;
        int w = opts.outWidth;
        int h = opts.outHeight;
        int size = 0;
        if (w <= ww && h <= hh) {
            size = 1;
        } else {
            double scale = w >= h ? w / ww : h / hh;
            double log = Math.log(scale) / Math.log(2);
            double logCeil = Math.ceil(log);
            size = (int) Math.pow(2, logCeil);
        }
        opts.inSampleSize = size;
        bitmap = BitmapFactory.decodeFile(srcPath, opts);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
//		XLog.i("大小1："+baos.toByteArray().length);

        while (baos.toByteArray().length > imageSize * 1024) {
            baos.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            quality -= 5;
//			XLog.i("大小："+baos.toByteArray().length);
        }
        try {
            baos.writeTo(new FileOutputStream(srcPath));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                baos.flush();
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


//	/**
//	 * 压缩图片至320*480再添加时间戳后保存
//	 * @param context
//	 * @param filename
//	 */
//	public static void compressAndSave(Context context,String filename) {
//		Log.i("tag","imageName4=:"+filename);
//		FileOutputStream fos = null;
//		StringBuffer buffer = new StringBuffer("开始压缩并保存图片，");
//		try {
//			String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.APP_NAME, "fmsdk");
//			File path = new File(storePath);
//			if (!path.exists())
//				path.mkdirs();
//			String imagePath = getH5ImagePath(filename,context);
//			buffer.append("imagePath="+imagePath);
//			int degree=readPictureDegree(imagePath);
//			buffer.append(" 被旋转角度degree="+degree);
//			//压缩尺寸大小
//			Bitmap bitmap = compress(context,imagePath);
//			if(degree==90||degree==270){
//				buffer.append(" 开始旋转图片，角度 = " + degree);
//				bitmap=rotaingImageView(degree, bitmap);
//			}
//			//添加时间戳
//			Bitmap hadTimeMarkBitmap = addTimeMark(context, bitmap);
//			//保存图片
//			if (hadTimeMarkBitmap != null)
//				compressAndSave(context,hadTimeMarkBitmap,imagePath,200);
//			else
//				compressAndSave(context,bitmap,imagePath,200);
//		} catch (Exception e) {
//
//		} finally {
//			try {
//				if (fos != null)
//					fos.close();
//			} catch (IOException e) {
//
//			}
//		}
//	}

    /**
     * 加时间戳
     *
     * @param bitmap
     * @return
     */
    public static Bitmap addTimeMark(Context context, Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }
        try {
            Date date = new Date(System.currentTimeMillis());
            String timeMark = DateFormat.format("yyyy-MM-dd HH:mm:ss", date)
                    .toString();
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            Bitmap tempBitmap = Bitmap.createBitmap(width, height,
                    Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(tempBitmap);
            Paint photoPaint = new Paint();
            photoPaint.setDither(true);
//			float textWidth = paint.measureText(timeMark);
            canvas.drawBitmap(bitmap, 0, 0, photoPaint);
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
            paint.setColor(Color.WHITE);
            paint.setShadowLayer(1, 1, 1, Color.BLACK);//设置黑色阴影
            paint.setTextSize(16);
            canvas.drawText(timeMark, 16, height - 16,
                    paint);//画到照片左下角
            canvas.save();
            canvas.restore();
            return tempBitmap;
        } catch (Exception e) {
            return null;
        }
    }
//	/**
//	 * 压缩图片至200k以内并保存指定路径
//	 * 大图先尺寸压缩再质量压缩
//	 * @param bitmap
//	 * @param path
//	 */
//	public static void compressAndSave(Context context,Bitmap bitmap,String path,int size){
//		if (size == 0){
//			size = 100;
//		}
//		//如果图片尺寸大于手机尺寸，就先尺寸压缩
//		DisplayMetrics metrics = getDisplayMetrics(context);
//		int height = metrics.heightPixels;
//		int width = metrics.widthPixels;
//		Bitmap temp = bitmap;
//		if (bitmap.getWidth() > width || bitmap.getHeight() > height){
//			temp = compress(context,bitmap,height,width);
//		}
//		if (temp == null)
//			temp = bitmap;
//		ByteArrayOutputStream baos = new ByteArrayOutputStream();
//		int quality = 100;
//		temp.compress(Bitmap.CompressFormat.JPEG, quality, baos);
//		while (baos.toByteArray().length > size * 1024) {
//			baos.reset();
//			temp.compress(Bitmap.CompressFormat.JPEG, quality, baos);
//			quality -= 10;
//			if(quality<0){
//				break;
//			}
//		}
//		try {
//			baos.writeTo(new FileOutputStream(path));
//			baos.flush();
//			baos.close();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}

    /**
     * 获取屏幕参数DisplayMetrics
     *
     * @param context
     * @return
     */
    public static DisplayMetrics getDisplayMetrics(Context context) {
        return context.getResources().getDisplayMetrics();
    }

    public static Bitmap compress(Context context, Bitmap bitmap, float ww, float hh) {
        if (bitmap == null)
            return null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        ByteArrayInputStream ios = new ByteArrayInputStream(bos.toByteArray());
        BitmapFactory.decodeStream(ios, null, opts);
        opts.inJustDecodeBounds = false;
        int w = opts.outWidth;
        int h = opts.outHeight;
        int be = 1;
        if (w > h && w > ww) {
            be = (int) (opts.outWidth / ww);
        } else if (w < h && h > hh) {
            be = (int) (opts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        opts.inSampleSize = be;
        opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
        opts.inPurgeable = true;
        opts.inInputShareable = true;
        ByteArrayInputStream ios2 = new ByteArrayInputStream(bos.toByteArray());
        Bitmap result = BitmapFactory.decodeStream(ios2, null, opts);
        try {
            ios.close();
            ios2.close();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return result;
    }


    public static void base64ToImage(String base64, String filePath) {
        try {
            byte[] bytes = Base64.decode(base64, Base64.DEFAULT);
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

            File file = new File(filePath);
            if (file.exists()) {
                return;
            }
            saveBitmapToJPG(bitmap, file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void saveBitmapToJPG(Bitmap bitmap, File file) throws IOException {
        Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(bitmap, 0, 0, null);
        OutputStream stream = new FileOutputStream(file);
        newBitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
        stream.close();
    }


    /**
     * 获取相册的所有图片
     *
     * @return
     */
    public static List<String> getAllPhotos(Context context) {
        List<String> photoPaths = new ArrayList<>();

        // 查询MediaStore以获取所有照片
        ContentResolver contentResolver = context.getContentResolver();
        Uri imageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        String[] projection = {MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA};
        Cursor cursor = contentResolver.query(imageUri, projection, null, null, null);

        if (cursor != null) {
            while (cursor.moveToNext()) {
                int columnIndexData = cursor.getColumnIndex(projection[1]);
                String photoPath = cursor.getString(columnIndexData);
                photoPaths.add(photoPath);
            }
            cursor.close();
        }

        return photoPaths;
    }

    /**
     * 获取相册所有视频文件
     *
     * @param context
     * @return
     */
    public static ArrayList<String> getAllVideoFromGallery(Context context) {
        ArrayList<String> videoList = new ArrayList<>();
        Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        String[] projection = {MediaStore.Video.VideoColumns.DATA};
        Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);

        if (cursor != null) {
            while (cursor.moveToNext()) {
                videoList.add(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA)));
            }
            cursor.close();
        }

        return videoList;
    }

}
